﻿using CommunityToolkit.Mvvm.ComponentModel;
using HslCommunication.ModBus;
using ProductionLine.Modules.ShareLib.Helpers;
using ProductionLine.Modules.ShareLib.Models;
using System;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ProductionLine.Modules.Index.ViewModels;

public partial class IndexViewModel : ObservableObject {
    #region 属性/字段
    [ObservableProperty]
    private  ModbusParams _modbusParams;
    private readonly GlobalConfig _globalConfig;

    private CancellationTokenSource _cts = new();

    [ObservableProperty]
    public ScadaReadData _scadaReadDataProp;//可观察属性,用于绑定到xaml页面

    private readonly ModbusTcpNet _modbusTcpNet;
    #endregion


    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="globalConfig"></param>
    /// <param name="options"></param>
    public IndexViewModel(GlobalConfig globalConfig) {
        _globalConfig = globalConfig;
        _modbusParams = globalConfig.ModbusParams;
        _scadaReadDataProp = globalConfig.ScadaReadDataProp;//初始化可观察属性
        InitReadDataDic2ScadaReadDataProp();

        #region modbus读取

        #endregion
    }



    /// <summary>
    /// 初始化ReadDataDic(数据字典)到ScadaReadDataProp(可观察属性)的映射
    /// </summary>
    private void InitReadDataDic2ScadaReadDataProp() {
     
        Task.Run(async () => {
            // 获取所有需要动态更新的属性,获取所有float和bool类型属性
            var properties = typeof(ScadaReadData)
            .GetProperties()
            .Where(p => p.PropertyType == typeof(float) || p.PropertyType == typeof(bool));

            while (!_cts.Token.IsCancellationRequested) {
                foreach (var property in properties) {
                    try {  // 动态设置属性值（支持类型扩展）
                        if (property.PropertyType == typeof(float)) {//如果是float类型
                            var value = _globalConfig.GetValue<float>(property.Name);//通过key从ReadDataDic获得value
                            property.SetValue(ScadaReadDataProp, value);//给property赋值
                        } else if (property.PropertyType == typeof(bool)) {//如果是bool类型
                            var value = _globalConfig.GetValue<bool>(property.Name);
                            property.SetValue(ScadaReadDataProp, value);
                        }//for循环完成之后,ScadaReadDataProp对象就被填满了
                    } catch (Exception e) {
                        Debug.WriteLine(e);
                    }
                }
                await Task.Delay(100);// 控制更新频率
            }
        });
    }
}